package com.symone.webcms.controller.web;

import com.alibaba.fastjson.JSONObject;
import com.symone.webcms.config.GlobalConfig;
import com.symone.webcms.controller.base.BaseController;
import com.symone.webcms.model.base.ResultMessage;
import com.symone.webcms.service.impl.FileUploadService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@Controller
@RequestMapping("/cms")
public class WebFileController extends BaseController {

    @Autowired
    private FileUploadService uploadService;

    @RequestMapping(value = "/file/index", method = RequestMethod.GET)
    @RequiresPermissions("sys:file:index")
    public ModelAndView fileList() {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("/admin/file/index");
        return mv;
    }

    @RequestMapping(value = "wangEditor/aliyun/saveImg", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadImgToOSS(@RequestParam("file") MultipartFile file) {
        logger.info("============>文件上传");
        JSONObject jsonObject = new JSONObject();
        try {

            if (null != file) {
                String uploadUrl = uploadService.aliyunUpload(file);
                jsonObject.put("errno", 0);
                jsonObject.put("data", getAliyunOSSUrl() + uploadUrl);
                return jsonObject;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonObject;
    }

    @RequestMapping(value = "wangEditor/local/saveImg", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject uploadImg(@RequestParam("file") MultipartFile file,HttpServletRequest request) {
        logger.info("============>文件上传");
        JSONObject jsonObject = new JSONObject();
        try {

            if (null != file) {
                ResultMessage rm = uploadService.localUpload(file,request,null,null);
                jsonObject.put("errno", 0);
                jsonObject.put("data", rm.get("data"));
                return jsonObject;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return jsonObject;
    }

    private String getAliyunOSSUrl() {
        String endpoint = GlobalConfig.getInstance().get("sys_aliyun_oss_endpoint");
        String bucketName = GlobalConfig.getInstance().get("sys_aliyun_oss_bucketname");
        return "http://" + bucketName + "." + endpoint + "/";
    }

}

